import $http from '../utils/http.js'
import router from '../routers/router.js'
import { Notification } from 'atelement'
const validcode = 'system/validcode'
const settersLogin = 'system/settersLogin'
const login = 'system/login'
const settersRoot = 'system/settersRoot'
const auth = 'system/auth'
const jumpUrl = 'system/jumpUrl'
const logout = 'system/logout'
const changPass = 'system/changePass'
const getAssetFollow = 'system/getAssetFollow'
const getFollowAsset = 'system/getFollowAsset'
const changeFollowAsset = 'system/changeFollowAsset'
const validationFilling = 'system/validationFilling'
const changeSize = 'system/changeSize'
const changeHeadFixed = 'system/changeHeadFixed'
const changeFooterFixed = 'system/changeFooterFixed'
const changeTheme = 'system/changeTheme'
const getTheme = 'system/getTheme'
const changeLeftMenu = 'system/changeLeftMenu'

const getPath = function (data) {
  if (data.path != null) {
    return data.path
  } else {
    return getPath(data.children[0])
  }
}

export default {
  state: {
    fixHeadMenu: false,
    fixFooterMenu: false,
    fixLeftMenu: false,
    topicValue: '',
    login: {
      username: '', // 用户名
      password: '', // 密码
      validcodeInput: '', // 用户输入的验证码
      validcode: {
        image: '' // 验证码图片
      }
    },
    changeSizeValue: '',
    showModelChangeInfo: false,
    menu: [], // 改角色拥有的菜单权限
    currentUser: {}, // 当前角色信息,
    showModelChangePass: false,
    changePasswordControlClose: false,
    assetTreeData: [],
    assetTreeDataChoose: [],
    device: [],
    project: {},
    perMsg: [{}],
    editableTabsValue: '/monitor/event',
    editableTabs: [],
    keepAliveInclude: []
  },
  actions: {
    [getTheme] ({ commit, state }, item) {
      $http.post('/api/getTheme', item).then(({ status, data } = {}) => {
        if (status === 'success') {
          data.fixed_footer === '1' ? (state.fixFooterMenu = true) : (state.fixFooterMenu = false)
          data.head_navigation === '1' ? (state.fixHeadMenu = true) : (state.fixHeadMenu = false)
          data.left_navigation === '1' ? (state.fixLeftMenu = true) : (state.fixLeftMenu = false)
          state.topicValue = data.theme_colour
        }
      })
    },
    [changeHeadFixed] ({ commit }, item) {
      $http.post('/api/ifFixedHeader', item).then(({ status, data } = {}) => {
        if (status === 'success') {
          // if (item) {
          //   Notification.success({
          //     title: '固定头部导航成功!'
          //   })
          // } else {
          //   Notification.success({
          //     title: '取消固定头部导航成功!'
          //   })
          // }
        }
      })
    },
    [changeLeftMenu] ({ commit }, item) {
      $http.post('/api/ifFixedLeftMenu', item).then(({ status, data } = {}) => {
        if (status === 'success') {
          // if (item) {
          //   Notification.success({
          //     title: '固定头部导航成功!'
          //   })
          // } else {
          //   Notification.success({
          //     title: '取消固定头部导航成功!'
          //   })
          // }
        }
      })
    },
    [changeFooterFixed] ({ commit }, item) {
      $http.post('/api/ifFixedFooter', item).then(({ status, data } = {}) => {
        if (status === 'success') {
          // if (item) {
          //   Notification.success({
          //     title: '固定页脚成功!'
          //   })
          // } else {
          //   Notification.success({
          //     title: '取消固定页脚成功!'
          //   })
          // }
        }
      })
    },
    [changeTheme] ({ state }, item) {
      $http.post('/api/changeTheme', item).then(({ status, data } = {}) => {
        if (status === 'success') {
          state.topicValue = item.val
          // Notification.success({
          //   title: '修改主题成功!'
          // })
        }
      })
    },
    [getFollowAsset] ({ commit }) {
      $http.get('/api/asset/tree/own').then(({ status, data } = {}) => {
        if (status === 'success') {
          commit(getFollowAsset, data)
        }
      })
    },
    [changeFollowAsset] (replace, data) {
      $http.put('/api/asset/tree/update', { asset_id: JSON.stringify(data) }).then(({ status } = {}) => {
        // console.info(status, msg, data)
        if (status === 'success') {
          Notification.success({
            title: '关注资产修改成功'
          })
          // commit();
        }
      })
    },
    [getAssetFollow] ({ commit }) {
      $http.get('/api/asset/tree').then(({ status, data } = {}) => {
        // console.info(status, msg, data)
        if (status === 'success') {
          commit(getAssetFollow, data)
        }
      })
    },
    [validcode] ({ commit }) {
      $http.get('/api/validcode').then(({ status, msg, data } = {}) => {
        if (status === 'success') commit(validcode, data)
        else {
          Notification.error({
            title: '验证码获取失败',
            message: msg
          })
        }
      })
    },
    [login] ({ dispatch, commit, state }, value) {
      commit(settersRoot, { value: '', key: 'editableTabsValue' })
      commit(settersRoot, { value: [], key: 'editableTabs' })
      commit(settersRoot, { value: [], key: 'keepAliveInclude' })
      $http.post('/api/auth', value).then(({ status, msg, data } = {}) => {
        if (status === 'success') {
          state.login = {
            username: '', // 用户名
            password: '', // 密码
            validcodeInput: '', // 用户输入的验证码
            validcode: {
              image: '' // 验证码图片
            }
          }
          commit(settersRoot, { value: data.menu, key: 'menu' })
          commit(settersRoot, { value: data.user, key: 'currentUser' })
          router.push(getPath(data.menu[0]))
          // router.push('/web/warnings/validate')
          // if (data.user.role_id === 1) router.push('/system/users')
          // else if (data.user.role_id === 2) router.push('/test')
          // else if (data.user.role_id === 3) router.push('/logger')
        } else {
          Notification.error({
            title: '登录失败',
            message: msg
          })
          dispatch(validcode)
        }
      })
    },
    async [auth] ({ dispatch, commit }) {
      let result = await $http.get('/api/auth')
      if (result) {
        let { status, data } = result
        if (status === 'success') {
          for (let i in data.menu) {
            for (let j in data.menu[i].children) {
              this._vm.$set(data.menu[i].children[j], 'expand', true)
            }
          }
          commit(settersRoot, { value: false, key: 'showModelChangePass' })
          commit(settersRoot, { value: data.menu, key: 'menu' })
          commit(settersRoot, { value: { ...data.user }, key: 'currentUser' })
          commit(settersRoot, { value: data.device, key: 'device' })
          commit(settersRoot, { value: data.project, key: 'project' })
        } else if (status === 'default') {
          commit(settersRoot, { value: false, key: 'changePasswordControlClose' })
          commit(settersRoot, { value: true, key: 'showModelChangePass' })
          Notification.warning({
            title: '请修改初始密码'
            // message:msg
          })
        } else {
          // Notification.warning({
          //     title:"没有权限，或权限已经失效",
          //     message:msg
          // })
          dispatch(logout)
          router.push('/timeout')
        }
      }
    },
    [jumpUrl] (replace, data) {
      router.push(data)
      // commit();
    },
    [logout] ({ dispatch, commit }) {
      $http.post('/api/auth/loginout').then(({ status } = {}) => {
        if (status === 'success') {
          dispatch(jumpUrl, '/timeout')
          commit(logout)
        }
      })
    },
    [changPass] ({ dispatch }, data) {
      $http.post('/api/auth/update', data).then(({ status, msg } = {}) => {
        if (status === 'success') {
          Notification.success({
            title: '密码修改成功，请重新登录'
          })
          dispatch(logout)
        } else {
          Notification.warning({
            title: '密码修改失败',
            message: msg
          })
        }
        // commit();
      })
    }
  },
  mutations: {
    [getFollowAsset] (state, data) {
      state.assetTreeDataChoose = data
    },
    [changeSize] (state, data) {
      state.changeSizeValue = data
    },
    [logout] (state) {
      state.login.username = ''
      state.login.password = ''
      state.login.validcodeInput = ''
    },
    [validcode] (state, data) {
      state.login.validcode = {
        image: 'data:image/bmp;base64,' + data.image
      }
    },
    [settersLogin] (state, data) {
      state.login[data.key] = data.value
    },
    [settersRoot] (state, data) {
      if (data.key === 'currentUser') {
        for (var i in data.value) {
          if (data.value[i] === null || data.value[i] === '默认节点' || data.value[i] === 'None') {
            data.value[i] = '-'
          }
        }
      }
      state[data.key] = data.value
    },
    [getAssetFollow] (state, data) {
      state.assetTreeData = data
    },
    [validationFilling] (state, data) {
      state.login.validcodeInput = data
    }
  }
}
